<?php

namespace app\api\controller;

use think\exception\HttpException;
use think\facade\Env;
use think\paginator\driver\Bootstrap;
use think\Request;

class Upload extends Common
{
    const UPLOAD_DIR = 'upload/';
    const ST_DIR = 'public/';

    /**
     * @param $dir
     * @param Request $request
     * @return string|\think\response\Json
     */
    public function upload($dir, Request $request)
    {
        if (!$request->has('images', 'file')) {
            return $this->returnJson(500, '请选择上传的文件');
        } else {
            $files = $request->file('images');
            $this->checkPath($dir);
//            $images = '';
            if ($files instanceof \think\File) {
                // 单个文件
                $images = $this->saveFile($dir, $files);
            } elseif (count($files) > 9) {
                return $this->returnJson(500, '上传的文件不能超过九个');
            } else {
                foreach ($files as $k => $file) {
//                    $images .= $this->saveFile($dir, $file) . ',';
                    $images[] = $this->saveFile($dir, $file);
                }
            }
            return $this->returnJson(200, 'ok', $images);
        }
    }

    /**
     * @param $dir
     * @return \think\Paginator
     */
    public function index($dir)
    {
        // 遍历文件夹
        $arr = $this->getAllFiles($this->getSavePath($dir));
        // 去除 不必要的路径
        $res = array_map(function ($v) {
            return $v = str_replace(Env::get('ROOT_PATH') . self::ST_DIR, '', $v);
        }, $arr);
        $curPage = input('get.page') ? input('get.page') : 1;//接收前段分页传值
        $listRow = input('get.size') ? input('get.size') : 10;//每页2行记录
        // 分割数组
        $showData = array_slice($res, ($curPage - 1) * $listRow, $listRow, false);
        // 数组中根据条件取出一段值，并返回
        return $this->returnJson(200, 'ok', Bootstrap::make($showData, $listRow, $curPage, count($res)));
    }

    private function getAllFiles($path)
    {
        $list = [];
        foreach (glob($path . '/*') as $item) {
            if (!is_dir($item)) {
                $list[] = $item;
            } else {
                $list = array_merge($list, $this->getAllFiles($item));
            }
        }
        return $list;
    }

    /**
     * 检查路径
     * @param $dir
     */
    private function checkPath($dir)
    {
        $savePath = $this->getSavePath($dir);
        if (!is_dir($savePath)) {
            mkdir($savePath, 0777, true);
        }
    }

    /**
     * 获取保存路径
     * @param $dir
     * @return string
     */
    private function getSavePath($dir)
    {
        return Env::get('ROOT_PATH') . self::ST_DIR . self::UPLOAD_DIR . $dir;
    }

    /**
     * 保存文件
     * @param $dir
     * @param \think\File $file
     * @return string
     */
    private function saveFile($dir, \think\File $file)
    {
        // 4M
        $info = $file->validate(['size' => 4 * 1024 * 1024,
            'ext' => 'jpg,jpeg,png,gif'])->move($this->getSavePath($dir));
        if (!$info) {
            // 上传失败获取错误信息
            throw new HttpException(422, $file->getError());
        } else {
            // 成功上传后 获取上传信息
            $filename = str_replace('\\', '/', $info->getSaveName());
            return self::UPLOAD_DIR . $dir . '/' . $filename;
        }
    }
}
